package siruna.WE.DeviceDependent.rendering;

import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;

import org.apache.http.MethodNotSupportedException;

import siruna.WE.DeviceDependent.AndroidApplication;
import siruna.WE.DeviceDependent.AndroidWidgetFactory;
import siruna.WE.DeviceDependent.Global;
import siruna.WE.DeviceDependent.Listener;
import siruna.WE.DeviceDependent.R;
import siruna.WE.core.Widget;
import siruna.WE.core.Constants.InputTypes;
import siruna.WE.core.model.Block;
import siruna.WE.core.model.EventHandler;
import siruna.WE.core.model.EventList;
import siruna.WE.core.model.FunctionalBlock;
import siruna.WE.core.model.VisualBlock;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class WidgetView extends Activity implements Listener {
	HashMap<String, Integer> views;
	AndroidWidgetFactory awf;
	LinearLayout layout;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		awf = new AndroidWidgetFactory(this);

		int widgetId = getIntent().getIntExtra("widgetId", -1);

		System.out.println("id: " + widgetId);
		if (widgetId != -1) {
			views = new HashMap<String, Integer>();

			// registreren om updates van visuele blokken te ontvangen
			((AndroidApplication) getApplication()).getReceiver()
					.addLuisteraar(this);

			Widget widget = ((AndroidApplication) getApplication())
					.getWidget(widgetId);

			System.out.println("widgetview" + widget);

			WebView wv = new WebView(this);
			wv.getSettings().setJavaScriptEnabled(true);
			wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
			wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
			WebSettings webSettings = wv.getSettings();
			webSettings.setSavePassword(false);
			webSettings.setSaveFormData(false);
			webSettings.setJavaScriptEnabled(true);
			webSettings.setSupportZoom(false);

			String html = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
			html += "<html><head><title>Widget</title></head><body>\n";

			for (String s : widget.getVisblocks().keySet()) {
				System.out
						.println(" " + s + " " + widget.getVisblocks().get(s));

				html += widget.getVisblocks().get(s).toHTML() + "\n";

			}
			
			
			
			html += "<script language=\"javascript\">\n";

			
			for (String s : widget.getFunctblocks().keySet()) {
				System.out
						.println(" " + s + " " + widget.getFunctblocks().get(s));

				html += widget.getFunctblocks().get(s).toHTML() + "\n";

			}
			
			

			
			for (EventList el : widget.getEventlists().values()) {
				System.out.println("MLML: " + el.getId());
				html += "function " + el.getId() + "(){\n";

				for (EventHandler eh : el.getEventHandlers()) {
					VisualBlock b = widget.getVisblocks().get(
							eh.getAttributes().get("DestinationId"));

					// attributeevent voorlopig de enige !
					if (eh.getAttributes().get("DestinationValue") != null) {

						System.out.println("if");
						// b.setAttribute(eh.getAttributes().get(
						// "DestinationAttribute"), eh.getAttributes()
						// .get("DestinationValue"));

						html += "var naar =  document.getElementById(\""
								+ b.getId() + "\");\n";

						html += changeValue_innerHTML("naar", "\""+eh
								.getAttributes().get("DestinationValue")+"\"");

					}

					// dataEvent
					// voorlopig alleen een source die een FunctionalBlock is
					else {
						System.out.println("else");

						for (String s : widget.getFunctblocks().keySet()) {
							// System.out.println("functblocks: " + s);

						}

						System.out.println("Hans: " + eh);

						for (String s : eh.getAttributes().keySet()) {
							// System.out.println("Hans:s: "
							// + eh.getAttributes().get(s));

						}


						Block f = null;
						
						if (eh.getAttributes().get("SourceId") != null) {

							f = widget.getVisblocks().get(
									eh.getAttributes().get("SourceId"));
							if(f!=null){
								html += "var van =  document.getElementById(\""
									+ f.getId() + "\");\n";
								
								
							}
							else{//==null
								f = widget.getFunctblocks().get(
										eh.getAttributes().get("SourceId"));
								html += "var van = "+f.getId()+";\n";
								;
								
								
							}
						}
						// FunctionalBlock

						else {
							//f = widget.getVisblocks().get(e.getSourceid());
						}

						if(f!=null){
					
						html += "var naar =  document.getElementById(\""
								+ b.getId() + "\");\n";

						html += changeValue_innerHTML("naar", "van.value");
						}
						
						
					}
				}
				html += "}\n";

			}

			html += "</script>\n";

			html += "</body></html>\n";

			wv.setWebViewClient(new WebViewClient() {
				@Override
				public boolean shouldOverrideKeyEvent(WebView view,
						KeyEvent event) {
					// TODO Auto-generated method stub
					return false;
				}

			});

			String mimeType = "text/html";
			String encoding = "utf-8";
			// this doenst work well,
			// link:http://www.mail-archive.com/android-developers@googlegroups.com/msg13390.html
			//wv.loadData(html)
			wv.loadDataWithBaseURL("fake://fake.com", html, mimeType, encoding,
					null);

			try {
				FileOutputStream fOut = openFileOutput("html.html",
						MODE_WORLD_READABLE);
				OutputStreamWriter osw = new OutputStreamWriter(fOut);
				osw.write(html);
				osw.flush();
				osw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			/*
			 * OLD int i = 0; for (String s : widget.keySet()) {
			 * System.out.println(i + " " + s + " " + widget.get(s)); View v =
			 * awf.getAndroidView(widget.get(s)); views.put(s, i); if (v !=
			 * null) { layout.addView(v); i++; } // TextView tv = new
			 * TextView(this); // tv.setText("ff"); // setContentView(tv);
			 * 
			 * }
			 */

			setContentView(wv);

		}
	}

	private String changeValue_innerHTML(String naar, String val) {
		String s = "";

		s += "if (" + naar + ".childNodes[0]){\n";
		s += naar + ".childNodes[0].nodeValue=" + val + ";\n";
		s += "} else if (" + naar + ".value){\n";
		s += naar + ".value=" + val + ";\n";
		s += "} else { //if (.innerHTML){ \n";
		s += naar + ".innerHTML=" + val + ";\n";
		s += "}";
		return s;
	}

	@Override
	public void update(int widgetId, String visBlockId) {
		// TODO Auto-generated method stub
		// widgetId
		System.out.println("new update: " + widgetId);

		System.out.println("new update: " + visBlockId);

		int pos = views.get(visBlockId);

		System.out.println("NP: " + ((AndroidApplication) getApplication()));
		System.out.println("NP: "
				+ ((AndroidApplication) getApplication()).getWidget(widgetId));
		VisualBlock vb = ((AndroidApplication) getApplication()).getWidget(
				widgetId).getVisblocks().get(visBlockId);

		View b1 = awf.getAndroidView(vb);

		System.out.println("layout: " + layout);
		System.out.println("pos: " + pos);

		layout.removeViewAt(pos);
		layout.addView(b1, pos);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu);

		MenuItem item = menu.add("Close");
		// item.setIcon(R.drawable.paint);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		super.onOptionsItemSelected(item);

		if (item.getTitle().equals("Close")) {
			this.setResult(Global.SUBACTIVITY_RESULTCODE_CHAINCLOSE);
			this.finish();

		}
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case Global.SUBACTIVITY_RESULTCODE_CHAINCLOSE:
			this.setResult(Global.SUBACTIVITY_RESULTCODE_CHAINCLOSE);
			this.finish();
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

}